<!--
 * @页面名称:复制全宗
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="card copyFonds">
    <div class="btn">
      <el-button type="primary" icon="CopyDocument" @click="copyClick">复制节点</el-button>
      <!-- 删除数据表 -->
      <el-popover :visible="popoverVisible" ref="popover" width="400" placement="right-start" trigger="click">
        <template #reference>
          <el-button type="primary" icon="Delete" style="margin-right: 16px" @click="popoverVisible = true">删除表数据</el-button>
        </template>
        <!-- 第一个删除数据表 -->
        <el-row type="flex" justify="center">
          <el-col :span="11">
            <el-divider content-position="left" class="elider">数据库选择</el-divider>
            <el-card class="box-card" shadow="never">
              <el-radio-group v-model="databaseRadio">
                <el-radio :label="0" class="elRadio">源数据库</el-radio>
                <el-radio :label="1" class="elRadio">目标数据库</el-radio>
              </el-radio-group>
            </el-card>
          </el-col>
          <!-- 第二个删除数据表 -->
          <el-col :offset="1" :span="11">
            <el-divider content-position="left" class="elider">节点选择</el-divider>
            <el-card class="box-card" shadow="never">
              <el-radio-group v-model="surfaceRadio">
                <el-radio :label="0" class="elRadio">清除选择节点表</el-radio>
                <el-radio :label="1" class="elRadio">清除所有表</el-radio>
              </el-radio-group>
            </el-card>
          </el-col>
        </el-row>
        <!-- 下方按钮 -->
        <div class="butch" style="text-align: right; margin-top: 10px">
          <el-button type="primary" @click="deleteSurface">删除</el-button>
          <el-button type="primary" @click="popoverVisible = false">取消</el-button>
        </div>
      </el-popover>
    </div>
    <!-- 调用页面 -->
    <!-- 调用源服务器页面 -->
    <splitpanes :dbl-click-splitter="false" style="display: flex; height: calc(100% - 42px)">
      <pane>
        <tree-operation :type="0" @getZtreeObj="getSourceObj" />
      </pane>
      <pane>
        <tree-operation :type="1" ref="target" @getZtreeObj="getTargetObj" />
      </pane>
    </splitpanes>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { ElLoading } from "element-plus";
import TreeOperation from "./TreeOperation.vue"; //服务器页面
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
//复制功能的表单
import copyFormData from "./copyFormData";
import useCurrentInstance from "@/utils/useCurrentInstance";

const { proxy } = useCurrentInstance();
const databaseRadio = ref(0); //数据库单选
const surfaceRadio = ref(0); //表单选
const popoverVisible = ref(false);
const sourceObj = ref(); //源树
const targetObj = ref(); //目标树
const value = ref("内容"); // 默认下拉选项
const options = ref([
  { value: "内容", key: 0 },
  { value: "子级", key: 1 }
]); //下拉选项
const selectView = ref();
const target = ref(); //目标服务器实例
// 注册signal服务
const signalrEvent = () => {
  // 注册signal服务(用于复制节点)
  proxy.signalr.off("SendFCCopyTheNode");
  proxy.signalr.on("SendFCCopyTheNode", (res: any) => {
    proxy.$showLoading({ tip: res });
    if (res.trim().startsWith("start")) {
      // 传输开始
      proxy.$showLoading({ tip: res });
    }
    if (res.trim().startsWith("stop")) {
      // 传输结束
      proxy.$hideLoading();
    }
  });
};
//获取源树对象
const getSourceObj = (ztreeObj: any) => {
  sourceObj.value = ztreeObj;
};
//获取目标树对象
const getTargetObj = (ztreeObj: any) => {
  targetObj.value = ztreeObj;
};
//复制功能
const copyClick = () => {
  // 判断是否选中数据
  if (sourceObj.value.getNodes().length > 0 && targetObj.value.getNodes().length > 0) {
    //获取选中
    let sourceNode = sourceObj.value.getSelectedNodes()[0];
    let targetNode = targetObj.value.getSelectedNodes()[0];
    //判断是否选中源服务器节点
    if (sourceNode !== undefined) {
      //判断是否选中目标服务器节点
      if (targetNode !== undefined) {
        //复制条件
        //如果是数据库数据并且类型小于6
        if (sourceNode.Type < 6) {
          proxy
            .$prompt("", "更改名称", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              inputValue: sourceNode.Name,
              closeOnClickModal: false
            })
            .then(({ value }: any) => {
              //获取更改名称的值
              let inputValue = value;
              console.log(value);
              //如果是不是全宗
              //如果type为1,就需要选中复制成为其子级或内容
              if (sourceNode.level != 0 && targetNode.level != 0 && sourceNode.Type == 1 && targetNode.Type == 1) {
                const h = proxy.$createElement;
                //select值
                let selectValue: any;
                proxy
                  .$msgbox({
                    title: "复制方式",
                    closeOnClickModal: false,
                    message: h("div", null, [
                      h("span", null, "复制为目标全宗的:"),
                      h(
                        "el-select",
                        {
                          props: {
                            value: value.value,
                            filterable: true
                          },
                          ref: "selectView",
                          class: "copySelect",
                          on: {
                            change: (e: any) => {
                              value.value = e;
                              selectView.value = e; // select值改变，回显到页面上
                            }
                          }
                        },
                        //遍历下拉框数组
                        [
                          options.value.map((opt: any) => {
                            return h("el-option", {
                              props: {
                                label: opt.value,
                                key: opt.key,
                                value: opt.value
                              }
                            });
                          })
                        ]
                      )
                    ]),
                    showCancelButton: true,
                    confirmButtonText: "确定",
                    cancelButtonText: "取消"
                  })
                  .then((res: any) => {
                    //默认值为0
                    if (value.value === "内容") {
                      selectValue = 0;
                    } else if (value.value === "子级") {
                      selectValue = 1;
                    }
                    //调用复制功能表单
                    let formData = copyEditName(sourceNode, targetNode, inputValue, selectValue, proxy.signalr.connectionId);
                    //调用复制api
                    proxy.$vueAxios.post("FondsCopy/CopyTheNode", { ...formData }, { noLoading: true }).then((res: any) => {
                      if (res.Mark) {
                        //1秒后调用查看全宗
                        setTimeout(() => {
                          target.value.viewProfile();
                        }, 1000);
                        proxy.$message({
                          type: "success",
                          message: "复制成功"
                        });
                      } else {
                        proxy.$message.error("请选择正确的目标节点");
                      }
                    });
                  });
              } else {
                let formData = copyEditName(sourceNode, targetNode, inputValue, sourceNode.Type, proxy.signalr.connectionId);
                proxy.$vueAxios.post("FondsCopy/CopyTheNode", { ...formData }, { noLoading: true }).then((res: any) => {
                  if (res.Mark) {
                    //1秒后调用查看全宗
                    setTimeout(() => {
                      target.value.viewProfile();
                    }, 1000);
                    proxy.$message({
                      type: "success",
                      message: "复制成功"
                    });
                  } else {
                    proxy.$message.error("请选择正确的目标节点");
                  }
                });
              }
            })
            .catch();
        } else {
          proxy
            .$confirm(`是否复制${sourceNode.Name}到目标服务器${targetNode.Name}`, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              closeOnClickModal: false
            })
            .then(() => {
              let formData = copyEditName(sourceNode, targetNode, sourceNode.Name, sourceNode.Type, proxy.signalr.connectionId);
              proxy.$vueAxios.post("FondsCopy/CopyTheNode", { ...formData }, { noLoading: true }).then((res: any) => {
                if (res.Mark) {
                  //1秒后调用查看全宗
                  setTimeout(() => {
                    target.value.viewProfile();
                  }, 1000);
                  proxy.$message({
                    type: "success",
                    message: "复制成功"
                  });
                } else {
                  proxy.$message.error("请选择正确的目标节点");
                }
              });
            })
            .catch();
        }
      } else {
        proxy.$message.error(`请选中要粘贴的目标节点`);
      }
    } else {
      proxy.$message.error(`请选中要复制的源节点`);
    }
  } else {
    let databaseName;
    //判断是哪条数据未选中
    sourceObj.value.getNodes().length == 0 ? (databaseName = "源数据库") : (databaseName = "目标数据库");
    proxy.$message.error(`请加载${databaseName}全宗`);
  }
};
//复制功能表单
const copyEditName = (sourceNode: any, targetNode: any, nodeName: any, copyType: any, connectionId: any) => {
  let formData = copyFormData.copyDataType(sourceNode, targetNode, nodeName, copyType, connectionId);
  return formData;
};
//删除选项
const deleteSelect = (obj: any, objName: string, objType: number) => {
  //判断内容是否为空
  if (obj.getNodes().length > 0) {
    //判断选项表 0清除选择节点表  1清除所有表
    if (surfaceRadio.value == 0) {
      //判断节点表是否选中
      if (obj.getSelectedNodes()[0] !== undefined) {
        //获取选中节点表的ID
        let Fonds_ID = obj.getSelectedNodes()[0].Fonds_ID;
        proxy
          .$confirm(`清除 ${objName} 下节点表数据, 是否继续?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            //表单提交
            const formData = {
              fonds_ID: Fonds_ID,
              type: objType,
              nodeSelect: 0
            };
            //删除表数据api
            proxy.$vueAxios.post("FondsCopy/DeleteTableData", formData).then((res: any) => {
              if (res.Mark) {
                proxy.$message({
                  type: "success",
                  message: "清除成功"
                });
              } else {
                proxy.$message.error("清除失败");
              }
            });
          });
      } else {
        proxy.$message.error(`请选中 ${objName} 要清除的节点`);
      }
    } else {
      //清除全部表
      proxy
        .$confirm(`清除 ${objName} 的全部表数据, 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then((res: any) => {
          const formData = {
            type: objType,
            nodeSelect: 1
          };
          //删除表数据api
          proxy.$vueAxios.post("FondsCopy/DeleteTableData", formData).then((res: any) => {
            if (res.Mark) {
              proxy.$message({
                type: "success",
                message: "清除成功"
              });
            } else {
              proxy.$message.error("清除失败");
            }
          });
        });
    }
  } else {
    proxy.$message.error(`请先加载 ${objName} 的全宗数据`);
  }
};
//清除选中
const clearSelected = (sourceObj: any, targetObj: any) => {
  //sourceObj源数据库,targetObj目标数据库
  sourceObj.cancelSelectedNode(sourceObj.getSelectedNodes()[0]);
  targetObj.cancelSelectedNode(targetObj.getSelectedNodes()[0]);
};
//删除表数据功能
const deleteSurface = () => {
  //获取对象
  //判断选中的数据库 0源数据库 1目标数据库
  if (databaseRadio.value == 0) {
    deleteSelect(sourceObj.value, "源数据库", 0);
  } else {
    deleteSelect(targetObj.value, "目标数据库", 1);
  }
  //清除选中状态
  clearSelected(sourceObj.value, targetObj.value);
};
onMounted(() => {
  signalrEvent();
});
</script>

<style scoped lang="scss">
.copyFonds {
  height: 100%;
  width: 100%;
}
</style>
